package md.NJavaBase;

import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;

//事件分发器
public class QWEventDispatcher {
    static  String Tag = "QWEventDispatcher";

    //增加监听
    public void addEventListener(String type,ICallbackQWEvent listener)
    {
        ArrayList<ICallbackQWEvent> evtList = m_Evts.get(type);
        if(evtList==null)
        {
            m_Evts.put(type,new ArrayList<ICallbackQWEvent>());
            evtList = m_Evts.get(type);
        }

        evtList.add(listener);
    }

    //移除监听
    public void  removeEventListener(String type,ICallbackQWEvent listener)
    {
        ArrayList<ICallbackQWEvent> evtList = m_Evts.get(type);
        if(evtList==null) return;

        for(int i=evtList.size()-1;i>=0;i--)
        {
            if(evtList.get(i) == listener)
                evtList.remove(i);
        }
    }

    //派送事件
    public void  dispatchEvent(QWEvent evt)
    {
        ArrayList<ICallbackQWEvent> evtList = m_Evts.get(evt.Type);
        if(evtList==null) return;

        ArrayList<ICallbackQWEvent> cpList = new ArrayList<ICallbackQWEvent>();
        for(int i=0;i<evtList.size();i++) cpList.add( evtList.get(i) );

        for(int i=0;i<cpList.size();i++)
        {
            ICallbackQWEvent o = cpList.get(i);
            try{
                Log.d(Tag,"dispatchEvent "+evt.Type);
                o.reCall(evt);
            }catch(Exception e)
            {
                Log.e(Tag,e.getMessage());
            }
        }
    }

    private HashMap<String, ArrayList<ICallbackQWEvent>> m_Evts = new HashMap<String, ArrayList<ICallbackQWEvent>>();
}
